import { useState, useEffect } from 'react'
import '../assets/css/cart.css'
import { LeftOutline } from 'antd-mobile-icons'
import { List, SwipeAction, Empty } from 'antd-mobile'
import { useLocation, useNavigate } from 'react-router-dom'
import { Tabs, } from 'antd-mobile'
import { Cartlist, Cartdelete } from '../request/app'
function Cart() {
       let Navigate = useNavigate()
       // 全选
       let [allCheck, allchange] = useState(false)
       //       购物车列表
       let [Cartlists, Usecart] = useState([])
       // 总价
       let [allPrice, allPrices] = useState(0)
       useEffect(() => {
              if (!JSON.parse(sessionStorage.getItem('xiaou'))) {
                     alert("去登录")
                     Navigate('/login')
                     return
              }
              Cartlist({
                     uid: JSON.parse(sessionStorage.getItem('xiaou')).uid
              })
                     .then(res => {
                            if (res.code == 200) {
                                   console.log(res, '购物车');
                                   Usecart([...res.list[1].content])
                            }
                     })
       }, [])
       useEffect(() => {

              // 合计金额
              price()
       })
       // 价格
       function price() {
              let sum = 0;
              Cartlists.map(item => {
                     // console.log(item,'111');
                     // console.log(item.okcheck,'222');
                     if (item.okcheck) {
                            sum += item.price * item.num;
                     }
              })
              allPrices(sum.toFixed(2))
       }
       // 全选事件
       function changAll() {
              //点击按钮取反变成true
              allchange(!allCheck)
              Cartlists.map(item => {
                     item.okcheck = !allCheck
              });
              Usecart([...Cartlists])
       }
       // // 单选事件
       function changone(i) {
              Cartlists[i].okcheck = !Cartlists[i].okcheck
              // console.log(Cartlists[i].okcheck);
              let arr = Cartlists.every(item => item.okcheck)
              allchange(arr)
              Usecart([...Cartlists])
       }
       // 点击删除事件
       function del(id) {
              console.log(id, '111');
              Cartdelete({
                     id
              }).then(res => {
                     console.log(res, '111');
              })
              Cartlist({
                     uid: JSON.parse(sessionStorage.getItem('xiaou')).uid
              })
                     .then(res => {
                            if (res.code == 200) {
                                   console.log(res, '购物车');
                                   Usecart([...res.list[1].content])
                            }
                     })
       }
       //       结算
       function jiesuan(e) {
              console.log(e, '结算');
              //    判断用户是否选择了一件商品
              if (Cartlists.some(item => item.okcheck)) {
                     // //      some一真为真 全假为假‘
                     // 先获取用户购买的数量
                     let num = 0;
                     // 获取用户选择的商品id
                     let val = "";
                     // 用户选择的购物车列表
                     let goodsDetail = [];
                     Cartlists.map(item => {
                            if (item.okcheck) {
                                   //    计算数量和
                                   num += item.num
                                   // id的拼接
                                   val += `,${item.id}`
                                   //       把选择的购物车列表推送
                                   goodsDetail.push(item)
                            }
                     });
                     // 定义一个对象去接受几个必要的参数
                     let objInfo = {
                            countmoney: allPrice,
                            countnumber: num,
                            idstr: val.slice(1),
                     }

                     // 把获取的订单对象存到本地
                     sessionStorage.setItem("objInfo", JSON.stringify(objInfo))
                     // 把选择的购物车列表数组加入到本地
                     sessionStorage.setItem("goodsDetail", JSON.stringify(goodsDetail))

                     Navigate('/indent')
              } else {
                     // 阻止默认动作
                     e.preventDefault();
                     alert("至少选择一件商品");
              }
       }
       // 加   
       function jia(i) {
              console.log(i, '下标');
              Cartlists[i].num++;
              Usecart([...Cartlists])
       }
       // 减
       function jian(i) {
              console.log(i, '下标');
              // 判断数量不能小于1
              if (Cartlists[i].num <= 1) {
                     Cartlists[i].num = 1;
              } else {
                     Cartlists[i].num--;
              }
              Usecart([...Cartlists])
       }
       return (
              <div>
                     <div className='page'>
                            {/* 头部 */}
                            <header>
                                   {/* 上部分 */}
                                   <div className='navigation '>
                                          <p>9:41</p>
                                          <p>信号</p>
                                   </div>
                                   {/* 下部分 */}
                                   <div className='battery'>
                                          <LeftOutline style={{ fontSize: 20, marginLeft: 10 }} />
                                          <p>
                                                 购物车
                                          </p>

                                   </div>
                            </header>
                            <article>
                                   {/* 标签页 */}
                                   <Tabs className='navibar'>
                                          <Tabs.Tab title='全部(20)' key='fruits' />
                                          <Tabs.Tab title='降价(4)' key='vegetables' />
                                          <Tabs.Tab title='常卖(2)' key='animals' />
                                          <Tabs.Tab title='分类' key='fenlei' />
                                   </Tabs>
                                   {/* 购物车商品 */}
                                   <div className='yangshi'>
                                          {
                                                 Cartlists.length == 0 ? <Empty
                                                        style={{ padding: '64px 0' }}
                                                        imageStyle={{ width: 128 }}
                                                        description='暂无数据'
                                                 /> : ""
                                          }
                                          {
                                                 Cartlists.map((item, idx) => {
                                                        return (
                                                               <div className='gouwu' key={item.id}>
                                                                      <List>
                                                                             <SwipeAction

                                                                                    // closeOnAction={false}
                                                                                    // closeOnTouchOutside={false}
                                                                                    rightActions={[
                                                                                           {
                                                                                                  key: 'delete',
                                                                                                  text: '删除',
                                                                                                  color: 'danger',

                                                                                           },

                                                                                    ]}
                                                                                    onAction={() => del(item.id)}
                                                                             >
                                                                                    <div className='cardcommod' >
                                                                                           <div>
                                                                                                  <input
                                                                                                         className='inp'
                                                                                                         type="checkbox"
                                                                                                         onChange={() => changone(idx)}
                                                                                                         checked={item.okcheck || ""}
                                                                                                  />
                                                                                           </div>
                                                                                           <div className='piccommodi'>
                                                                                                  <img src={item.img} alt="" />
                                                                                           </div>
                                                                                           <div className='xiang'>
                                                                                                  <div>
                                                                                                         <span>{item.goodsname}</span>
                                                                                                         <span>{item.titel1}</span>
                                                                                                  </div>
                                                                                                  <div className='jiang'>
                                                                                                         <a href="#">比加入时降低￥100元</a>
                                                                                                         <p>￥{item.price}
                                                                                                                <s>￥1099</s>
                                                                                                         </p>
                                                                                                         <div className='shanchu'>
                                                                                                                <span onClick={() => jian(idx)}>-</span>
                                                                                                                <span>{item.num}</span>
                                                                                                                <span onClick={() => jia(idx)}>+</span>
                                                                                                         </div>

                                                                                                  </div>
                                                                                           </div>
                                                                                    </div>

                                                                             </SwipeAction>
                                                                      </List>


                                                               </div>
                                                        )
                                                 })
                                          }
                                   </div>
                                   {/* 结算 */}
                                   <div className='addbtn'>
                                          <div className='addquan'>
                                                 <input
                                                        className='inp'
                                                        type="checkbox"
                                                        onChange={() => changAll()}
                                                        checked={allCheck || ""}
                                                 />全选
                                          </div>
                                          <div className='addspan'>
                                                 合计<span>￥{allPrice}</span>
                                          </div>
                                          <div className='buttonconf'>
                                                 <p onClick={(e) => jiesuan(e)}>去结算
                                                 </p>


                                          </div>
                                   </div>




                            </article>
                     </div>

              </div>
       )
}

export default Cart